define(['jquery', 'bootstrap', 'backend', 'table', 'form', '/static/libs/layui/layui.js'], function ($, undefined, Backend, Table, Form, Layui) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'pricereviewmanagent/pricing_review_items/index' + location.search,
                    add_url: 'pricereviewmanagent/pricing_review_items/add',
                    edit_url: 'pricereviewmanagent/pricing_review_items/edit',
                    del_url: 'pricereviewmanagent/pricing_review_items/del',
                    multi_url: 'pricereviewmanagent/pricing_review_items/multi',
                    import_url: 'pricereviewmanagent/pricing_review_items/import',
                    detail_url: 'pricereviewmanagent/pricing_review_items/detail',
                    table: 'pricing_review_items',
                }
            });

            var table = $("#table");
            var projectConfig = Config.projectConfig;

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                height: 700,
                fixedColumns: true,
                fixedNumber: 3,
                columns: [
                    [
                        {checkbox: true,formatter: function(value, row, index) {
                            return {
                                disabled: !(Config.childrenAdminIds.indexOf(row.admin_id) > -1)
                            };
                        }},
                        {field: 'id', title: __('序号'),sortable:true},
                        {field: 'name', title: __('Name'), align: 'left',cellStyle:function (value,row,index,field) {
                            return {
                                css: {
                                    "min-width": "150px",
                                    "white-space": "nowrap",
                                    "text-overflow": "ellipsis",
                                    "overflow": "hidden",
                                    "max-width":"300px",
                                    'cursor':"pointer"
                                }
                            };
                        }, formatter:function (value, row, index) {
                            return "<a href='javascript:void(0);' style='color: #4397fd' class='btn-dialog' " +
                                        "data-url='pricereviewmanagent/pricing_review_items/detail/ids/"+row.id+"' data-title='项目详情' data-area=[\"100%\",\"100%\"]  title='"+row.name+"'>" + row.name + "</a>";
                        }},
                        {field: 'description', title: __('Description'),cellStyle:function (value,row,index,field) {
                                return {
                                    css: {
                                        "min-width": "150px",
                                        "white-space": "unset",
                                        "text-overflow": "ellipsis",
                                        "overflow": "hidden",
                                        "max-width":"300px",
                                        'cursor':"pointer"
                                    }
                                };
                            },formatter:function (value,row,index,field) {
                                var span=document.createElement('span');
                                span.setAttribute('title',value);
                                span.innerHTML = value;
                                return span.outerHTML;
                            }
                        },
                        {field: 'unit', title: __('Unit')},
                        {field: 'quantity', title: __('Quantity')},
                        {field: 'unit_price', title: __('Unit_price'),sortable:true},
                        {field: 'total_price', title: __('Total_price')},
                        {field: 'appraise_price', title: __('Appraise_price')},
                        {field: 'project.project_name', title: __('Project_name'), operate: 'LIKE', formatter:function (value, row, index) {
                            return "<a href='javascript:void(0);' style='color: #4397fd' class='btn-dialog' " +
                                        "data-url='project/detail/ids/"+row.project_id+"' data-title='项目详情' data-area=[\"100%\",\"100%\"] >" + row.project.project_name + "</a>";
                        }},
                        {field: 'project.project_address', title: __('Project_address'), operate: 'LIKE'},
                        {field: 'project.pricing_date', title: __('Pricing_date'),sortable:true, operate: 'RANGE',datetimeFormat:'YYYY-MM-DD', formatter: Table.api.formatter.datetime, addclass:'datetimerange',},
                        {field: 'project.project_class', title: __('Project_class'), searchList: projectConfig.project_class, formatter: Table.api.formatter.normal},
                        {field: 'project.project_bulid_cost', title: __('Project_bulid_cost'), operate:'BETWEEN'},
                        {field: 'project.project_scale', title: __('Project_scale'), operate:'BETWEEN'},
                        // {field: 'square_build_cost', title: __('Square_build_cost'), operate:'BETWEEN'},
                        {field: 'project.build_unit', title: __('Build_unit')},
                        {field: 'project.construction_unit', title: __('Construction_unit')},
                        {field: 'project.structure_type', title: __('Structure_type'), searchList: projectConfig.structure_type, formatter: function (value, row, index) {
                            return projectConfig.structure_type[value] || '-';
                        }},
                        {field: 'project.build_cost_type', title: __('Build_cost_type'), searchList: projectConfig.build_cost_type, formatter: function (value, row, index) {
                            return projectConfig.build_cost_type[value] || '-';
                        }},
                        {field: 'project.build_form', title: __('Build_form'), searchList: projectConfig.build_form, formatter: function (value, row, index) {
                            return projectConfig.build_form[value] || '-';
                        }},
                        {field: 'project.taxation_type', title: __('Taxation_type'), searchList: projectConfig.taxation_type, formatter: function (value, row, index) {
                            return projectConfig.taxation_type[value] || '-';
                        }},
                        {field: 'project.contract_no', title: __('Contract_no')},
                        // {field: 'start_date', title: __('Start_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'end_date', title: __('End_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'real_start_date', title: __('Real_start_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'real_end_date', title: __('Real_end_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'project_params', title: __('Project_params'), operate: 'LIKE'},
                        // {field: 'pricing_method', title: __('Pricing_method')},
                        // {field: 'pricing_basis', title: __('Pricing_basis')},
                        // {field: 'pricing_inventory', title: __('Pricing_inventory')},
                        // {field: 'senior_editor_date', title: __('Senior_editor_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'quota_days', title: __('Quota_days')},
                        // {field: 'contract_days', title: __('Contract_days')},
                        // {field: 'real_days', title: __('Real_days')},
                        // {field: 'prepared_date', title: __('Prepared_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        // {field: 'prepared_by', title: __('Prepared_by'), operate: 'LIKE'},
                        // {field: 'build_unit', title: __('Build_unit'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'compilation_unit', title: __('Compilation_unit'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'review_unit', title: __('Review_unit'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        // {field: 'contacts', title: __('Contacts'), operate: 'LIKE'},
                        // {field: 'contact_mobile', title: __('Contact_mobile'), operate: 'LIKE'},
                        // {field: 'constact_email', title: __('Constact_email'), operate: 'LIKE'},
                        // {field: 'project_files', title: __('Project_files'), operate: false, formatter: Table.api.formatter.files},
                        {field: 'admin.nickname', title: __('Admin_id')},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        // {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'pricereviewmanagent/pricing_review_items/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name')},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'pricereviewmanagent/pricing_review_items/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'pricereviewmanagent/pricing_review_items/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        import: function () {
            console.log('Layui', layui)
            layui.config({
                base: '/static/libs/layui/modules/step-lay/',
                extend: {
                    step: 'step' // 模块名与路径对应
                }
            }).use([ 'form', 'step', 'upload'], function () {
                var $ = layui.$
                    , form = layui.form
                    , element = layui.element
                    , step = layui.step
                    , upload = layui.upload;

                step.render({
                    elem: '#stepForm',
                    filter: 'stepForm',
                    width: '100%', //设置容器宽度
                    stepWidth: '850px',
                    height: '500px',
                    stepItems: [{
                        title: '基础设置'
                    }, {
                        title: '上传文件'
                    }, {
                        title: '导入数据'
                    }]
                });


                form.on('submit(formStep)', function (data) {
                    console.log('stepForm', data)
                    $.ajax({
                        url: 'pricereviewmanagent/pricing_review_items/importset',
                        type: 'POST',
                        data: data.field,
                        success: function (res) {
                            if (res.code == 1) {
                            }
                        }
                    })
                    step.next('#stepForm');
                    return false;
                });
                let file = '';
                //拖拽上传
                upload.render({
                    elem: '#uploadFile'
                    ,url: 'ajax/upload' //此处用的是第三方的 http 请求演示，实际使用时改成您自己的上传接口即可。
                    ,accept: 'file'
                    ,exts: 'xlsx|xls'
                    ,size: 1024*10
                    ,choose: function(obj){
                        //将每次选择的文件追加到文件队列
                        var files = obj.pushFile();
                        
                        //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
                        obj.preview(function(index, file, result){
                          console.log('preview1',index); //得到文件索引
                          console.log('preview2',file); //得到文件对象
                        //   console.log('preview3',result); //得到文件base64编码，比如图片
                          
                          //obj.resetFile(index, file, '123.jpg'); //重命名文件名，layui 2.3.0 开始新增
                          
                          //这里还可以做一些 append 文件列表 DOM 的操作
                          
                          //obj.upload(index, file); //对上传失败的单个文件重新上传，一般在某个事件中使用
                          //delete files[index]; //删除列表中对应的文件，一般在某个事件中使用
                        });
                    }
                    // ,progress: function(n, elem, res, index){
                    //     var percent = n + '%' //获取进度百分比
                    //     element.progress('demo', percent); //可配合 layui 进度条元素使用
                        
                    //     console.log('progress1', elem); //得到当前触发的元素 DOM 对象。可通过该元素定义的属性值匹配到对应的进度条。
                    //     console.log('progress2',res); //得到 progress 响应信息
                    //     console.log('progress3',index); //得到当前上传文件的索引，多文件上传时的进度条控制，如：
                    //     element.progress('demo', n + '%'); //进度条
                    //   }
                    ,done: function(res){
                        layer.msg('上传成功');
                        // element.progress('demo', '100%'); //进度条
                        layui.$('#uploadDemoView').removeClass('layui-hide').find('a').html(res.data.filename).data('downloader-url', res.data.fullurl).data('downloader-title', res.data.filename);
                        console.log(res)
                        file = res.data.url;
                        step.next('#stepForm');
                        $.ajax({
                            url: 'pricereviewmanagent/pricing_review_items/import_preview',
                            type: 'POST',
                            data: {
                                file: res.data.url
                            },
                            
                            success: function (res) {
                                if (res.code == 1) {
                                    const renderData = {
                                        items: res.data.data || []
                                    };
                                    // 带错误捕获的模板渲染
                                    try {
                                        const html = Template('listtpl', renderData);
                                        $('#tablebody').empty().html(html);
                                        Form.api.bindevent($("form[role=form]"));
                                    } catch (e) {
                                        console.error('模板渲染错误:', e);
                                        Toastr.error('数据解析失败');
                                    }
                                }
                           }
                        })
                    }
                });

                form.on('submit(formStep2)', function (data) {
                    console.log('stepForm2', data)
                    if (data.field.file == '') {
                        Toastr.error('请上传文件');
                        return false;
                    }
                    step.next('#stepForm');
                    return false;
                });
                form.on('submit(formStep3)', function (data) {
                    console.log('stepForm3', data)
                    if (file == '') {
                        Toastr.error('请上传文件');
                        return false;
                    }
                    $.ajax({
                        url: 'pricereviewmanagent/pricing_review_items/import',
                        type: 'POST',
                        data: {
                            file: file,
                            project_id:Config.info.id
                        },
                        success: function (res) {
                            if (res.code == 1) {
                                Toastr.success(res.msg);
                                setTimeout(function () {
                                    parent.location.reload();
                                },1500)
                            } else {
                                Toastr.error(res.msg);
                            }
                            
                        }
                    })
                    return false;
                });

                $('.pre').click(function () {
                    step.pre('#stepForm');
                });

                $('.next').click(function () {
                    step.next('#stepForm');
                });
            })
            Controller.api.bindevent();
        },
        importset:function () {
            layui.use(['form'], function () {
                var $ = layui.$
                    , form = layui.form
                    , element = layui.element
                    , upload = layui.upload;
            })
            Controller.api.bindevent();
        },
        detail: function () {
            $(document).on('click','#edits',function () {
                var id=$('#ids').val();
                Fast.api.open("pricereviewmanagent/pricing_review_items/edit?ids="+id, "项目编辑",{
                    shadeClose: false,
                    shade: false,
                    maxmin: false,
                    moveOut: false,
                    scrollbars:false,
                    area:["95%","95%"],
                    callback:function(value){
                        location.reload();
                    },
                });

            })
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                let originalData = []; // 用于存储原始数据
                let batchtimes = 0;
                let curtimes = 0;
                let lastrow = 0;
                let lastlevel = 0;
                let lastfirstpid = 0;
                let lasttwopid = 0;
                let lastpid = 0;
                $("#c-listfile").change(function () {
                    var listfile = $(this).val();
                    if (listfile) {
                        var that = this
                        that.layerIndex =layer.load(0,{ shade: 0.3 });
                        $.ajax({
                            url: "pricereviewmanagent/pricing_review_items/import_preview",
                            data: {listfile: listfile},
                            type: "post",
                            complete: function(){
                                layer.close(that.layerIndex);
                            },
                            success: function (res) {
                                if (res.code == 1) {
                                    originalData = res.data.data;
                                    batchtimes = res.data.batchtimes;
                                    layer.msg(res.msg,{time:1000},function (){
                                        var htm = `<table class="table table-striped table-config" id="normaledit">
                                                    <tbody>
                                                    <tr>
                                                        <td width="60">Excel行号</td>
                                                        <td>项目编码</td>
                                                        <td>项目名称</td>
                                                        <td width="100">项目特征描述</td>
                                                        <td>计量单位</td>
                                                        <td width="60">工程量</td>
                                                        <td width="100">综合单价(元)</td>
                                                        <td width="60">合价(元)</td>
                                                        <td width="60">暂估价(元)</td>
                                                    </tr>
                                                    `;
                                        for (var i=0;i<originalData.length;i++){
                                            numcount = originalData[i].hang
                                            htm += `<tr>
                                                        <td>${originalData[i].hang}</td>
                                                        <td>${originalData[i].code}</td>
                                                        <td>${originalData[i].name}</td>
                                                        <td>${originalData[i].description}</td>
                                                        <td>${originalData[i].unit}</td>
                                                        <td>${originalData[i].quantity}</td>
                                                        <td>${originalData[i].unit_price}</td>
                                                        <td>${originalData[i].total_price}</td>
                                                        <td>${originalData[i].appraise_price}</td>`;
                                            htm += ` </tr>`;
                                        }
                                        htm += `</tbody>
                                                    </table>`;
                                        $("#wechat").empty();
                                        $("#wechat").html(htm);
                                    });
                                } else {
                                    layer.msg(res.msg);
                                    return false;
                                }
                            }
                        });
                    }
                });
                var submit = function(form, success, error, submit) {
                    if (form.size() === 0) {
                        Toastr.error("表单未初始化完成,无法提交");
                        return false;
                    }
                    if (typeof submit === 'function') {
                        if (false === submit.call(form, success, error)) {
                            return false;
                        }
                    }
                    var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
                    type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
                    var url = form.attr("action");
                    url = url ? url : location.href;
                    // 调整 serialize 方法以收集修改过的数据
                    var file = form.find("input[name=file]");
                    // 构建最终的提交数据
                    var params = $.param({file: file.size() > 0 ? file.val() : '', 'curtimes':curtimes, lastrow, project_id:$('#c-project_id').val(), lastlevel, lastfirstpid, lastpid, lasttwopid});
                    // 修复当存在多选项元素时提交的 BUG
                    var multipleList = $("[name$='[]']", form);
                    if (multipleList.size() > 0) {
                        var postFields = form.serializeArray().map(function (obj) {
                            return obj.name;
                        });
                        $.each(multipleList, function (i, j) {
                            if (postFields.indexOf($(this).prop("name")) < 0) {
                                params[$(this).prop("name")] = '';
                            }
                        });
                    }
                
                    // 调用 Ajax 请求方法
                    // 返回一个新的Promise对象
                    return new Promise(function(resolve, reject) {
                        Fast.api.ajax({
                            type: type,
                            url: url,
                            data: params,
                            dataType: 'json',
                            complete: function (xhr) {
                                var token = xhr.getResponseHeader('__token__');
                                if (token) {
                                    $("input[name='__token__']").val(token);
                                }
                            }
                        }, function (data, ret) {
                            $('.form-group', form).removeClass('has-feedback has-success has-error');
                            if (data && typeof data === 'object') {
                                // 刷新客户端 token
                                if (typeof data.token !== 'undefined') {
                                    $("input[name='__token__']").val(data.token);
                                }
                                // 调用客户端事件
                                if (typeof data.callback !== 'undefined' && typeof data.callback === 'function') {
                                    data.callback.call(form, data);
                                }
                            }
                            if (typeof success === 'function') {
                                if (false === success.call(form, data, ret)) {
                                    return false;
                                }
                            }
                            resolve(ret); // 解析Promise
                        }, function (data, ret) {
                            if (data && typeof data === 'object' && typeof data.token !== 'undefined') {
                                $("input[name='__token__']").val(data.token);
                            }
                            if (typeof error === 'function') {
                                if (false === error.call(form, data, ret)) {
                                    return false;
                                }
                            }
                            reject(ret); // 拒绝Promise
                        });
                        return true;
                    });
                }
                $('#import-submit').click(function () {
                    var that = this,
                    form = $('#import-form'),
                    submitBtn = $(".layer-footer [type=submit]", form);
                    submitBtn.addClass("disabled");
                    async function submitForm(i) {
                        curtimes = i;
                        try {
                            const rets = await submit(form, function(data, ret){
                                if (ret.code == 1) {
                                    lastrow = ret.data.lastrow;
                                    lastlevel = ret.data.lastlevel;
                                    lastfirstpid = ret.data.lastfirstpid;
                                    lasttwopid = ret.data.lasttwopid;
                                    lastpid = ret.data.lastpid;
                                }
                                if ((i + 1) === batchtimes) {
                                    submitBtn.removeClass("disabled");
                                    // 提示及关闭当前窗口
                                    var msg = ret.hasOwnProperty("msg") && ret.msg !== "" ? ret.msg : __('Operation completed');
                                    parent.Toastr.success(msg);
                                    parent.$(".btn-refresh").trigger("click");
                                    var index = parent.Layer.getFrameIndex(window.name);
                                    parent.Layer.close(index);
                                }
                            }, function(data, ret){
                                if ((i + 1) === batchtimes) {
                                    submitBtn.removeClass("disabled");
                                }
                            });
                            // 如果需要根据`ret`做进一步处理
                            // console.log('Submit result:', rets);
                        } catch (error) {
                            // 处理错误情况
                            console.error('Error submitting form:', error);
                        }
                    }
                    
                    (async function processNext() {
                        for (let i = 0; i < batchtimes; i++) {
                            await submitForm(i); // 等待当前提交完成
                        }
                    })();
                    
                    return false
                })
            }
        }
    };
    return Controller;
});
